package com.hardson.toolkit.swing;

import java.awt.Component;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseWheelEvent;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;

public class PanelScrollPane extends JScrollPane {

	private static final long serialVersionUID = 1L;

	/**
	 * 面板滚动像素的倍数。默认情况下，JScrollPane对于JPanel的滚动步长为1像素
	 */
	protected int rate = 1;

	protected PanelScrollListener mouseWheelListener = null;

	public PanelScrollPane() {
		this(25);
	}

	public PanelScrollPane(final JPanel view, final int vsbPolicy, final int hsbPolicy,
			final int rate) {
		super(view, vsbPolicy, hsbPolicy);
		this.rate = rate;
		this.init();
		this.mouseWheelListener = new PanelScrollListener(view, this.rate);
		this.addMouseWheelListener(this.mouseWheelListener);

	}

	public PanelScrollPane(final JPanel view, final int rate) {
		this(view, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED, rate);
	}

	public PanelScrollPane(final int rate) {
		super();
		this.rate = rate;
		this.init();
	}

	private void init() {
		this.setOpaque(false);
		this.getViewport().setOpaque(false);
	}

	@Override
	public void setViewport(final JViewport viewport) {
		super.setViewport(viewport);
		if (this.mouseWheelListener != null) {
			this.removeMouseWheelListener(this.mouseWheelListener);
		}
		JPanel view = (JPanel) viewport.getView();
		if (view != null) {
			this.mouseWheelListener = new PanelScrollListener(view, this.rate);
			this.addMouseWheelListener(this.mouseWheelListener);
		}
	}

	@Override
	public void setViewportView(final Component view) {
		super.setViewportView(view);
		if (this.mouseWheelListener != null) {
			this.removeMouseWheelListener(this.mouseWheelListener);
		}
		if (view != null) {
			this.mouseWheelListener = new PanelScrollListener((JPanel) view, this.rate);
			this.addMouseWheelListener(this.mouseWheelListener);
		}
	}

	public void clearBorder() {
		this.setBorder(BorderFactory.createEmptyBorder());
	}

	private class PanelScrollListener extends MouseAdapter {
		/**
		 * 被滚动的面板
		 */
		private JPanel panelToScroll = null;

		/**
		 * 倍
		 */
		private int rate = 1;

		/**
		 *
		 * @param panelToScroll
		 *            被滚动的面板
		 * @param rate
		 *            倍
		 */
		public PanelScrollListener(final JPanel panelToScroll, final int rate) {
			this.panelToScroll = panelToScroll;
			this.rate = rate;
		}

		@Override
		public void mouseWheelMoved(final MouseWheelEvent e) {
			Rectangle rec = this.panelToScroll.getVisibleRect();
			int rotation = e.getWheelRotation();
			int y = (int) rec.getY() + (this.rate * rotation);
			rec.setBounds((int) rec.getX(), y, (int) rec.getWidth(), (int) rec.getHeight());
			this.panelToScroll.scrollRectToVisible(rec);
		}

	}
}
